<?php
require_once ('../../config/include_paths.php');
require_once('config.php');
$pageTitle = SITE_NAME.' - Administration - Dashboard';
require_once('dbconnect.php');	// database connect script.
$error = "";
	$msg = "";
	$fileElementName = 'value';
	if(!empty($_FILES[$fileElementName]['error']))
	{
		switch($_FILES[$fileElementName]['error'])
		{

			case '1':
				$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
				break;
			case '2':
				$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
				break;
			case '3':
				$error = 'The uploaded file was only partially uploaded';
				break;
			case '4':
				$error = 'No file was uploaded.';
				break;

			case '6':
				$error = 'Missing a temporary folder';
				break;
			case '7':
				$error = 'Failed to write file to disk';
				break;
			case '8':
				$error = 'File upload stopped by extension';
				break;
			case '999':
			default:
				$error = 'No error code avaiable';
		}
	}elseif(empty($_FILES['value']['tmp_name']) || $_FILES['value']['tmp_name'] == 'none')
	{
		$error = 'No file was uploaded..';
	}else 
	{
			//set the form values
			$table = $_GET['table'];
			$id = $_GET['id'];
			$file = $_FILES['value']['name'];
			//find the old file
			$query_string = "SELECT file from ".$table." WHERE id = ".$id;  
			$result = mysql_query($query_string) or die(mysql_error());
			while ($row = mysql_fetch_assoc($result)) {
				$oldFile = $row['file']; // get old file name
			}
			//see if there is more than one old file
			$query_string = "SELECT count(*) from ".$table." WHERE file = '".$oldFile."'";  
			$result = mysql_query($query_string) or die(mysql_error());
			if ($row = mysql_fetch_array($result)) {
				$numFiles = $row[0];
			}
			//delete old file if the only one is this one
			if ($numFiles == 1) {
				$path = APP_ROOT.'/public_html/uploads/' . $oldFile;
				@unlink($path );
				}
			move_uploaded_file($_FILES['value']['tmp_name'], 
			APP_ROOT.'/public_html/uploads/' . $_FILES['value']['name']);
			echo "<strong>".$_FILES['value']['name']."<strong>"; // return name to form
			@unlink($_FILES['value']);	//for security reason, we force to remove all uploaded files
			foreach ($_POST as $key => $value) 
			{unset ($_POST[$key]);}//delete all the POST vars so we can set only what we need for processTable function
			$_POST['id'] = $id; // now set the POST vars for processTable funtion
			$_POST['file'] = $file;
			processTable($table);
	}		


?>